#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import sys

from common import cleaner
from common.common import exter_attack
from common.const import ExecuteResultEnum, SysData
from common.job_const import JobNameConst
from common.parse_parafile import ParamFileUtil
from common.util.check_utils import is_valid_id
from gaussdbt.single import LOGGER
from gaussdbt.single.comm.gst_single_const import GstSingleConst
from gaussdbt.single.comm.utils.gst_single_comm_utils import GstSingleCommonUtil
from gaussdbt.single.resource.gst_single_resource import GstSingleResource


@exter_attack
def distribute_task(task_name, pid, param_dict):
    gst_single_resource = GstSingleResource(pid, param_dict)
    task_name_func_mappings = {
        JobNameConst.CHECK_APPLICATION: {
            "exec_task_func": gst_single_resource.exec_check_application,
            "output_result_func": gst_single_resource.output_action_result
        }
    }
    exec_func_dict = task_name_func_mappings.get(task_name)
    if not exec_func_dict:
        LOGGER.error(f"Unsupported task action: %s, pid: %s.", task_name, pid)
        err_msg = f"Unsupported task action: {task_name}."
        GstSingleCommonUtil.output_action_result(pid, ExecuteResultEnum.INTERNAL_ERROR.value, message=err_msg)
        return
    # 调用对应的执行函数
    action_ret = exec_func_dict["exec_task_func"]()
    if exec_func_dict.get("output_result_func"):
        exec_func_dict["output_result_func"](action_ret)


@exter_attack
def main():
    if len(sys.argv) < 3:
        LOGGER.error("Number of argv wrong. ")
        return ExecuteResultEnum.INTERNAL_ERROR.value
    args = sys.argv[1:]
    task_name, pid = args[0], args[1]
    LOGGER.info(f"Start executing gaussdbt single task, task name: %s, pid: %s.", task_name, pid)
    # 校验pid
    if not is_valid_id(pid):
        LOGGER.warn(f'pid is invalid!')
        sys.exit(1)
    try:
        param_dict = ParamFileUtil.parse_param_file_and_valid_by_schema(pid, GstSingleConst.JSON_SCHEMA_PATH)
    except Exception:
        LOGGER.exception(f"Parse param file failed, task name: {task_name}, pid: {pid}.")
        err_msg = "Parse parameter file failed."
        GstSingleCommonUtil.output_action_result(pid, ExecuteResultEnum.INTERNAL_ERROR.value, message=err_msg)
        return ExecuteResultEnum.INTERNAL_ERROR.value
    try:
        distribute_task(task_name, pid, param_dict)
    except Exception:
        LOGGER.exception(f"Distribute gaussdbt single resource task failed. Task Name: {task_name}, Pid: {pid}.")
        return ExecuteResultEnum.INTERNAL_ERROR.value
    LOGGER.info(f"Execute task success. Task Name: %s, Pid: %s.", task_name, pid)
    return ExecuteResultEnum.SUCCESS.value


if __name__ == '__main__':
    SysData.SYS_STDIN = sys.stdin.readline()
    try:
        sys.exit(main())
    finally:
        cleaner.clear(SysData.SYS_STDIN)
        LOGGER.debug('Clear environment variables successfully.')
